package com.iflytek.springboot_medicine.service;

import com.iflytek.springboot_medicine.entity.DingDanOrder;
import com.iflytek.springboot_medicine.mapper.DingDanOrdersMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class DingDanOrdersService {
    @Autowired
    DingDanOrdersMapper dingDanOrdersMapper;

    public List<DingDanOrder> getOrdersByUserName(String userName) {
        // 清理用户名参数
        String cleanedUserName = userName != null ? userName.replace("\"", "").trim() : null;
        
        System.out.println("Service层接收到的原始用户名: [" + userName + "]");
        System.out.println("原始用户名长度: " + (userName != null ? userName.length() : 0));
        System.out.println("原始用户名字符编码: " + (userName != null ? userName.getBytes().length : 0));
        
        System.out.println("清理后的用户名: [" + cleanedUserName + "]");
        System.out.println("清理后的用户名长度: " + (cleanedUserName != null ? cleanedUserName.length() : 0));
        System.out.println("清理后的用户名字符编码: " + (cleanedUserName != null ? cleanedUserName.getBytes().length : 0));
        
        // 先查询所有订单，用于调试
        List<DingDanOrder> allOrders = dingDanOrdersMapper.selectAllOrders();
        System.out.println("所有订单数量: " + allOrders.size());
        if (!allOrders.isEmpty()) {
            System.out.println("第一条订单的用户名: [" + allOrders.get(0).getUserName() + "]");
            System.out.println("第一条订单的用户名长度: " + allOrders.get(0).getUserName().length());
            System.out.println("第一条订单的用户名字符编码: " + allOrders.get(0).getUserName().getBytes().length);
        }
        
        // 使用COUNT查询检查是否存在匹配的记录
        int count = dingDanOrdersMapper.countOrdersByName(cleanedUserName);
        System.out.println("COUNT查询结果: " + count);
        
        // 然后查询指定用户的订单
        List<DingDanOrder> ordersByUserName = dingDanOrdersMapper.selectOrdersByName(cleanedUserName);
        System.out.println("Service层查询结果: " + ordersByUserName);
        
        if (ordersByUserName != null) {
            System.out.println("查询到的订单数量: " + ordersByUserName.size());
            if (!ordersByUserName.isEmpty()) {
                System.out.println("第一条订单数据: " + ordersByUserName.get(0));
                System.out.println("第一条订单的用户名: [" + ordersByUserName.get(0).getUserName() + "]");
                System.out.println("第一条订单的用户名长度: " + ordersByUserName.get(0).getUserName().length());
                System.out.println("第一条订单的用户名字符编码: " + ordersByUserName.get(0).getUserName().getBytes().length);
            }
        }
        return ordersByUserName;
    }
}
